package com.yanfan.modbus.codec;

import com.yanfan.common.ByteUtil;
import com.yanfan.common.annotation.SysProtocol;
import com.yanfan.common.constant.YanfanConstant;
import com.yanfan.common.core.mq.DeviceReport;
import com.yanfan.common.core.mq.MQSendMessageBo;
import com.yanfan.common.core.mq.message.DeviceData;
import com.yanfan.common.core.mq.message.FunctionCallBackBo;
import com.yanfan.common.exception.ServiceException;
import com.yanfan.modbus.ModbusUtils;
import com.yanfan.modbus.exception.ModbusTransportException;
import com.yanfan.modbus.frame.abs.ModbusResponse;
import com.yanfan.protocol.base.protocol.IProtocol;
import io.netty.buffer.ByteBuf;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@SysProtocol(name = "ModbusTcp协议", protocolCode = YanfanConstant.PROTOCOL.ModbusTcp, description = "系统内置ModbusTcp解析协议")
public class ModbusTcpMessageProtocol implements IProtocol {
    @Override
    public DeviceReport decode(DeviceData data, String clientId) {
        try {
            ByteBuf buf = data.getBuf();
            int transactionId = buf.readUnsignedShort();
            int protocolId = buf.readUnsignedShort();
            if (protocolId != ModbusUtils.MODBUS_TCP_PROTOCOL_ID) {
                throw new ModbusTransportException("un supported protocol id: " + ByteUtil.dumpHex((byte) protocolId));
            }
            buf.readUnsignedShort(); // Length, which we don't care about.

            // Create the modbus response.
            ModbusResponse response = ModbusResponse.createModbusResponse(buf);
        } catch (Exception e) {
            log.error("=>解码异常[{}]", e.getMessage());
            throw new ServiceException(e.getMessage());
        }


        return null;
    }


    @Override
    public FunctionCallBackBo encode(MQSendMessageBo message) {
        return null;
    }
}
